import React, { Component } from 'react'
// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'

import { asyncIncrement, increment, decrement } from '../../redux/actions/count'

// 定义UI组件
class Count extends Component {

    // 加法
    increment = () => {
        let { value } = this.selectNumber
        // 通知redux操作数据
        this.props.increment(value * 1)
    }

    // 减法
    decrement = () => {
        let { value } = this.selectNumber
        // 通知redux操作数据
        this.props.decrement(value * 1)
    }

    // 奇数再加
    incrementIfOdd = () => {
        let { value } = this.selectNumber
        const { count } = this.props
        if (count % 2 !== 0) {
            this.props.increment(value * 1)
        }
    }

    // 异步加
    incrementAsync = () => {
        let { value } = this.selectNumber
        // 通知redux操作数据
        this.props.asyncIncrement(value * 1, 1000)
    }

    render() {
        const { count, personArr } = this.props
        return (
            <div>
                <h1>我是Count组件</h1>
                <h4>当前求和为：{ count }, 下方组件总人数为: { personArr.length }</h4>
                <select ref={ c => this.selectNumber = c }>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
                <button onClick={ this.increment } style={ { margin: '5px' } }>
                    +
                </button>
                <button onClick={ this.decrement } style={ { margin: '5px' } }>
                    -
                </button>
                <button onClick={ this.incrementIfOdd } style={ { margin: '5px' } }>
                    当前求和为奇数再加
                </button>
                <button onClick={ this.incrementAsync } style={ { margin: '5px' } }>
                    异步加
                </button>
            </div>
        )
    }
}


// 使用 connect()()创建并暴露一个Count的容器组件
export default connect(
    (state) => ({ count: state.count, personArr: state.person }),
    {
        increment,
        decrement,
        asyncIncrement
    }
)(Count)
